import { get } from 'lodash';
import { delay } from 'redux-saga';
import { takeEvery, put, select } from 'redux-saga/effects';
import {
  fetchData,
  toggleErrorInfo,
  setVerifyCodeCountDown,
  startVerifyCodeCountDown,
} from '../actions';
import { fetchServerDataSaga } from './network';

function* toggleErrorInfoSaga({ payload }) {
  const { visible } = payload;
  if (visible) {
    yield delay(1500);
    yield put(toggleErrorInfo({ visible: false }));
  }
}
function* startVerifyCodeCountDownSaga() {
  const state = yield select();
  const active = get(state, ['common', 'verifyCodeCountDown', 'active'], true);
  const remaining = get(
    state,
    ['common', 'verifyCodeCountDown', 'remaining'],
    0
  );

  if (active) return;

  for (let i = remaining; i > 0; i--) {
    const state = yield select();
    const correct = get(
      state,
      ['common', 'verifyCodeCountDown', 'correct'],
      false
    );
    // 如果被修正过，将 i 设置为被修正过后的剩余时间
    if (correct) {
      i = get(state, ['common', 'verifyCodeCountDown', 'remaining'], 0);
    }

    yield put(
      setVerifyCodeCountDown({
        correct: false,
        active: i > 0, // 当 i > 0 时才是活跃的
        remaining: i,
      })
    );
    yield delay(1000);
  }
  yield put(
    setVerifyCodeCountDown({
      correct: false,
      active: false,
      remaining,
    })
  );
}

export default function*() {
  yield takeEvery(fetchData.toString(), fetchServerDataSaga);
  yield takeEvery(toggleErrorInfo.toString(), toggleErrorInfoSaga);
  yield takeEvery(
    startVerifyCodeCountDown.toString(),
    startVerifyCodeCountDownSaga
  );
}
